/**
 * 
 */
package info.niwota.web;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

/**
 * @author qiangli
 *
 */
public class SetupPeerActivity extends Activity {

	private static final String TAG = "SetupPeerActivity";

	private EditText peerPassword;

	private EditText peerJid;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.peer_account);

		initRes();
	}

	private void initRes() {
		peerJid = (EditText) findViewById(R.id.peer_username);
		peerPassword = (EditText) findViewById(R.id.peer_password);
	}

	private void loadPreferences() {
		final SharedPreferences p = PreferenceManager
				.getDefaultSharedPreferences(this);
		//

		peerJid.setText(p.getString(Preferences.XMPP_JID, null));
		//
		showPassword(p);
	}
	
	private void showPassword(SharedPreferences p) {
		// password is special
		peerPassword.setText(null);
		if (Preferences.isXmppConfigured(this)) {
			peerPassword.setHint("********");
		}
	}

	@Override
	protected void onPause() {
		try {
			savePreferences();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();

		loadPreferences();
	}

	private void savePreferences() throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "savePreference");
		}
		final SharedPreferences p = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor ed = p.edit();

		ed.putString(Preferences.XMPP_JID, trim(peerJid.getText()
				.toString()));
		//
		String ctext = peerPassword.getText().toString();
		if (!TextUtils.isEmpty(ctext)) {
			ed.putString(Preferences.XMPP_PASSWORD, ctext);
		}
		ed.commit();
		//
		showPassword(p);
	}

	private String trim(String s) {
		if (s == null) {
			return "";
		}
		return s.trim();
	}
}
